package model

import (
	"net/http"

	"github.com/gorilla/securecookie"
	"github.com/gorilla/sessions"
)

var store = func() *sessions.CookieStore {
	s := sessions.NewCookieStore(securecookie.GenerateRandomKey(32))
	// set one day for session life.
	s.MaxAge(86400)
	return s
}()

type Session struct {
	sess *sessions.Session
}

func NewSession(r *http.Request) *Session {
	sess, _ := store.Get(r, "Moft-Session")
	return &Session{sess: sess}
}

func (s *Session) SetValues(values map[string]interface{}) *Session {
	for k, v := range values {
		s.sess.Values[k] = v
	}
	return s
}

// the default is empty string.
func (s *Session) GetString(key string) string {
	vv, ok := s.sess.Values[key]
	if !ok {
		return ""
	}
	v, ok := vv.(string)
	if !ok {
		return ""
	}
	return v
}

// the default is false.
func (s *Session) GetBool(key string) bool {
	vv, ok := s.sess.Values[key]
	if !ok {
		return false
	}
	v, ok := vv.(bool)
	if !ok {
		return false
	}
	return v
}

func (s *Session) Get(key interface{}) interface{} {
	return s.sess.Values[key]
}

func (s *Session) Save(w http.ResponseWriter, r *http.Request) error {
	return s.sess.Save(r, w)
}

func (s *Session) DeleteAll() *Session {
	for k := range s.sess.Values {
		delete(s.sess.Values, k)
	}
	return s
}
